package com.icookie.shuatim.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icookie.shuatim.api.dao.UserMapper;
import com.icookie.shuatim.api.service.UserInfoService;
import com.shuatim.common.utils.IdGen;
import com.shuatim.common.utils.Result;
import com.shuatim.model.wechat.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : issuser ✌️
 * @date : 2019/4/18 11:23
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserMapper, User> implements UserInfoService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 第三方用户登录处理逻辑
     * 先根据第三方的id判断数据库中是否有此用户，
     * 如果有那么直接返回用户信息，
     * 如果没有，那么插入一条用户信息到表中，然后返回此用户信息
     *
     * @param userInfo 用户信息
     * @return User
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public User thirdLogin(User userInfo) {
        List list = listMaps();
        User thirdUser = userMapper.selectOne(new QueryWrapper<User>().eq("third_party_user_id", userInfo.getThirdPartyUserId()));
        //首先查询是否有此用户
        if (thirdUser == null) {
            //如果昵称重复，那么在昵称后面加个4位长的随机数
            String nickname = userInfo.getNickName();
            if (userMapper.isNicknameOccupied(null, nickname)) {
                nickname = nickname + "_" + StringUtils.substring(IdGen.uuid(), 0, 4);
                userInfo.setNickName(nickname);
            }
            userMapper.insert(userInfo);
            thirdUser = userMapper.selectOne(new QueryWrapper<User>().eq("third_party_user_id", userInfo.getThirdPartyUserId()));
        }
        return thirdUser;
    }

    @Override
    public Result setUserSign(String signature, User user) {
        user.setDescription(signature);
        userMapper.updateById(user);
        return Result.ok();
    }
}
